package course.cmsc436.medicationmanager;

import java.util.Calendar;
import java.util.Date;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import course.cmsc436.medication.Medication;

public class AlarmScheduler {
	/* Uses alarm's times per day and times arraylist info to schedule all
	 * relevant alarms.
	 */
	private static String TAG = AlarmScheduler.class.getSimpleName();
	
	public static void scheduleAlarm(Context c, Medication m) {
		c = c.getApplicationContext();
		Intent i = new Intent(c, AlarmActivity.class);
		String name = m.getProprietaryName();
		
		AlarmManager am = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
		
		int num = 0;
		for(Date d : m.getTimes()) {
			Calendar now = Calendar.getInstance();
			Calendar then = Calendar.getInstance();
			then.setTime(d);
			while(then.before(now)) {
				then.add(Calendar.DATE, 1);
			}
			Log.d(TAG, "Time: "+ (then.getTimeInMillis() - now.getTimeInMillis()));
			Uri.Builder b = new Uri.Builder();
			b.scheme("medication");
			b.opaquePart(name);
			b.appendPath(""+num);
			Uri uri = b.build();
			i.setData(uri);
			i.putExtra("med", m.getProprietaryName());
			i.putExtra("numPills", ""+m.getPillsPerDose());
			Log.d(TAG, then.toString());
			PendingIntent pi = PendingIntent.getActivity(c, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
			am.setRepeating(AlarmManager.RTC_WAKEUP, then.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
			Log.d(TAG, "Set alarm " + num);
			num++;
		}
	}
	
	/* Uses medication's identifying info to cancel all alarms associated with
	 * it (after a call to scheduleAlarm).
	 */
	public static void cancelAlarm(Context c, Medication m) {
		c = c.getApplicationContext();
		Intent i = new Intent(c, AlarmActivity.class);
		String name = m.getProprietaryName();
		
		AlarmManager am = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
		
		for(int num = 0; num < 4; num++) {
			Log.d(TAG, "Test");
			Uri.Builder b = new Uri.Builder();
			b.scheme("medication");
			b.opaquePart(name);
			b.appendPath(""+num);
			Uri uri = b.build();
			i.setData(uri);
			i.putExtra("med", m.getProprietaryName());
			try {
				PendingIntent pi = PendingIntent.getActivity(c, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
				am.cancel(pi);
				pi.cancel();
				num++;
			} catch(Exception e) {
				Log.e(TAG, "Error canceling alarms", e);
			}
		}
	}	
}
